package cas.ihep.hmss;

import cas.ihep.hmss.hdfsin.HdfsIn;
import cas.ihep.hmss.hdfsout.HdfsOut;
import org.apache.hadoop.mapred.JobClient;

import java.net.URI;
import java.util.concurrent.Callable;

public class Task implements Callable<org.apache.hadoop.mapreduce.Job> {
//    private static final File tmpdir=new File("/tmp");
//    private static final File basedir=new File("/afs/ihep.ac.cn/users/y/yinqiao");
//    private static final String shell_code="export JAVA_HOME=/usr/lib/jvm/jre\n" +
//            "export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:guava-19.0.jar:GridFTPJar.jar\n"+
//            "exec hadoop jar hadoopms.jar cas.ihep.";

    private Job subJob;
    private JobClient jclient;

    Task(JobClient client,Job job){
        subJob=job;
        jclient=client;
    }

    @Override
    public org.apache.hadoop.mapreduce.Job call() throws Exception {
        URI uri = new URI(subJob.destPath);//截取destpath中path的部分
        JobSubmit submit;
        if ("hdfs".equals(uri.getScheme())) {
            submit = new HdfsIn();
        } else {
            submit = new HdfsOut();
        }
        return submit.submit(jclient, subJob.cores, subJob.srcPath, new URI(subJob.destPath).getPath());
//        String[] cmds={"bash","-c",null};
//        try(Server.TempFile list = new Server.TempFile("list", ".txt", tmpdir)) {
//            try(PrintWriter fout=new PrintWriter(new FileOutputStream(list.get()))) {
//                for (int i = 0; i < subJob.srcPath.size(); i++) {
//                    fout.println(subJob.srcPath.get(i));
//                }
//            }
//            URI uri = new URI(subJob.destPath);//截取destpath中path的部分
//            ProcessBuilder builder = new ProcessBuilder();
//            builder.directory(basedir);
//            StringBuilder strbuilder = new StringBuilder(shell_code);
//            if ("hdfs".equals(uri.getScheme())) {//判断是导入还是导出
//                strbuilder.append("HdfsIn.HdfsIn");
//            } else {
//                strbuilder.append("HdfsOut.HdfsOut");
//            }
//            strbuilder.append(" -libjars GridFTPJar.jar,guava-19.0.jar ").append(list.getAbsolutePath());
//
//            strbuilder.append(' ').append(uri.getPath()).append(' ').append(subJob.cores);
//            cmds[2] = strbuilder.toString();
//            builder.command(cmds);
//            builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
//            builder.redirectError(ProcessBuilder.Redirect.INHERIT);
//            Process process = builder.start();
//            if(process.waitFor()!=0){
//                System.err.println("Submit job failed: "+subJob.jid);
//            }
//            return null;
//        }
    }
}
